package com.neuedu.service.impl;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.neuedu.config.NeueduException;
import com.neuedu.entity.PmsOrder;
import com.neuedu.entity.PmsRegist;
import com.neuedu.mapper.PmsOrderMapper;
import com.neuedu.mapper.PmsRegistMapper;
import com.neuedu.service.PayService;
import com.neuedu.service.PmsOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.service.PmsRegistService;
import com.neuedu.util.PayContent;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 王禹
 * @since 2025-08-13
 */
@Service
public class PmsOrderServiceImpl extends ServiceImpl<PmsOrderMapper, PmsOrder> implements PmsOrderService {
    @Resource
    PmsOrderService pmsOrderService;
    @Resource
    PayService payService;
    @Override
    public boolean updatePay(HttpServletRequest request) throws AlipayApiException {
        if (payService.check(request)) {
            String outTradeNo = request.getParameter("out_trade_no");
            return pmsOrderService.updateActiveByNo(outTradeNo, (byte)2);
        }
        throw new NeueduException("支付失败");
    }
    public boolean updateActiveByNo(String no, byte active) {
        PmsOrder pmsOrder = new PmsOrder();
        pmsOrder.setActive(active);
        UpdateWrapper<PmsOrder> wrapper = new UpdateWrapper<>();
        wrapper.eq("no", no);
        return this.update(pmsOrder, wrapper);
    }

    @Override
    public List<PmsOrder> getOrder(String registerNo, LocalDate createDate) {
        QueryWrapper<PmsOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("register_no", registerNo)
                .eq("create_date", createDate)
                .eq("active", 1);
        return this.list(wrapper);
    }

    @Override
    public String payment(String no, String total, String type) throws AlipayApiException, JsonProcessingException {
        PayContent payContent = new PayContent();
        payContent.setProduct_code("FAST_INSTANT_TRADE_PAY");
        payContent.setOut_trade_no(no);
        payContent.setTotal_amount(total);
        payContent.setSubject(type);
        payContent.setBody(type);
        return payService.pay(payContent);
    }
}
